import { createRouter, createWebHistory } from 'vue-router';
import pinia from '@/store/index';
import { Local } from '@/utils/storage';
import { User } from '@/store/user';
import { routeConfig as routes } from './routeConfig';
// 引入扩展函数
import transitionExtend from "./transition-extend";
import { setLanguage } from "@/languages/index"
import { Page } from "@/store/page";

const userStore = User(pinia);
let router = createRouter({
  history: createWebHistory(),
  routes
});
router = transitionExtend(router);

const getQueryParams = (url: string) => {
  const paramArr = url.slice(url.indexOf("?") + 1).split("&");
  const params: any = {};
  paramArr.map((param: any) => {
    const [key, val] = param.split("=");
    params[key] = decodeURIComponent(val);
  });
  return params;
}

let currRouteName: string = ''
// let pageLoadingTimer: any = null
router.beforeEach(async (to: any, _from: any, next: any) => {
  currRouteName = ''
  if (to.name != _from.name && to.name != 'home') {
    Page(pinia).setPageLoading(true)
  }

  // 第三方链接进入聊天室
  const queryParams = getQueryParams(location.href)
  if ((window.location.href.indexOf('chatList') != -1) && queryParams.device_id) {
    const deviceId = queryParams.device_id;
    const lang = queryParams.lang;

    Local.set('deviceid', deviceId || '')
    Local.set('iscocos', true)
    setLanguage(lang, true)
    return next()
  }
  if (['/chatList', '/chatRoom', '/friendsList', '/shortcut'].includes(to.path)) {
    return next();
  }
  // console.error('登录状态', userStore.isLocalLoggedIn)
  if (userStore.isLocalLoggedIn) {
    if (!['deposit', 'depositNext'].includes(to.name)) {
      Local.remove('curDiscountData');
    }
    next()
  } else {
    if (['home', 'activity', 'me', 'vip', 'activityDetail', 'gameDetail', 'searchGames', 'hotGameDetail', 'chatList', 'chatRoom', 'friendsList', 'shortcut', 'categoryPage'].includes(to.name)) {
      next()
    } else {
      next(false)
      await User(pinia).setLogin(true)
    }
  }

})


router.afterEach((to: any, _from: any) => {
  if (_from.meta.deep >= to.meta.deep) { // 返回上一页时滚动到上一页记录的位置
    try {
      const scrollY = parseInt(sessionStorage.getItem('scrollY_' + to.name) || '0')
      if (Number(scrollY)) {
        window.scrollTo(0, scrollY)
        setTimeout(() => {
          window.scrollTo(0, scrollY)
        }, 0)
        if (to.name == 'home') { // 兼容个首页渲染时间
          setTimeout(() => {
            window.scrollTo(0, scrollY)
          }, 120)
        }
      }
    } catch { }
  }
  currRouteName = to.name
  Page(pinia).setPageLoading(false)
})
export default router;

// 这里记录滚动位置
window.addEventListener('scroll', () => {
  sessionStorage.setItem('scrollY_' + currRouteName, window.scrollY.toString())
})
// document.querySelector('#app')?.addEventListener('scroll', (e) => {
//   console.error('滚动位置', e)
// })
